package middleware

import (
	"ginblog/utils"
	"ginblog/utils/errmsg"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
	"time"
)
var JwtKey  = []byte(utils.JweKey)
type MyClaims struct {
	Username string `json:"username"`
	jwt.StandardClaims
}

// 生成token
func SetToken(username string) (string,int)  {
	expireTime := time.Now().Add(10 * time.Hour)
	SetClimas := MyClaims{
		username,
		jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(),
			Issuer: "ginblog",
		},

	}
   	req := jwt.NewWithClaims(jwt.SigningMethodHS256,SetClimas)
   	token,err := req.SignedString(JwtKey)
	if err != nil {
		return "",errmsg.ERROR
	}
	return token,errmsg.SUCC
}
//验证 token
func CheckToken(token string) (*MyClaims,int)  {
	setToken,_ :=jwt.ParseWithClaims(token,&MyClaims{}, func(token *jwt.Token) (interface{}, error) {
		return JwtKey,nil
	})
	if key,_ := setToken.Claims.(*MyClaims);  setToken.Valid {
		return key,errmsg.SUCC
	} else {
		return nil,errmsg.ERROR
	}
}

// jwt 中间件
var code int
func JwtToken() gin.HandlerFunc  {
	return func(c *gin.Context) {
		tokenHeader := c.Request.Header.Get("Authorization")
		code = errmsg.SUCC
		if tokenHeader == "" {
			code =  errmsg.ERROR
			//c.Abort()
			//return
		}
		checkToken := strings.SplitN(tokenHeader," ",2)
		if len(checkToken) != 2 && checkToken[0] != "Bearer" {
			code = errmsg.ERROR
			c.Abort()
		}
		key , Tcode := CheckToken(checkToken[1])
		if Tcode == errmsg.ERROR {
			code = errmsg.ERROR
			c.Abort()
		}
		if time.Now().Unix() > key.ExpiresAt {
			code = errmsg.ERROR
			c.Abort()
		}
		c.JSON(http.StatusOK,gin.H{
			"code":code,
			"message":errmsg.GetErrorMsg(code),
		})
		c.Set("username",key.Username)
		c.Next()
	}
	
}
